// UdpClient.cc
#include <iostream>
#include <string>
#include <cstring>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <pthread.h>
#include "Terminal.hpp"
#include "log.hpp"

Log log;

enum
{
    SOCKET_ERR = 1,
    BIND_ERR
};

void Usage(std::string proc)
{
    std::cout << "\n\rUsage: " << proc << " serverip serverport\n" << std::endl;;
}

struct ThreadData
{
    struct sockaddr_in server;
    int sockfd;
};

void *recv_message(void *args)
{
    // OpenTerminal();  // 输出重定向
    ThreadData *td = static_cast<ThreadData*>(args);
    char buffer[1024];  // 保存接收到的消息

    while (true)
    {
        // 接收
        struct sockaddr temp;
        socklen_t len = sizeof(temp);
        ssize_t s = recvfrom(td->sockfd, buffer, sizeof(buffer) - 1, 0, &temp, &len);
        if (s < 0)
        {
            log(Warning, "recvfrom error, errno: %d, err message: %s", errno, strerror(errno));
            continue;
        }
        buffer[s] = 0;
        std::cerr << buffer << std::endl;  // 输出重定向到了2，所以这里向cerr输出
    }
}
void *send_message(void *args)
{
    ThreadData *td = static_cast<ThreadData*>(args);
    std::string message;  // 保存要发送的消息
    socklen_t len = sizeof(td->server);

    std::string welcome = "I am coming...";
    sendto(td->sockfd, welcome.c_str(), welcome.size(), 0, (struct sockaddr*)&td->server, len);

    while (true)
    {
        // 发送
        std::cout << "Please Enter@ ";
        std::getline(std::cin, message);
        sendto(td->sockfd, message.c_str(), message.size(), 0, (struct sockaddr*)&td->server, len);
    }
}

// ./udpclient serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    struct ThreadData td;

    // 1. 创建udp socket
    td.sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (td.sockfd < 0)
    {
        log(Fatal, "socket create error, errno: %d, err message: %s", errno, strerror(errno));
        exit(SOCKET_ERR);
    }
    log(Info, "socket create success, socket: %d", td.sockfd);

    // 2.1 构建发送对象 - 服务端
    bzero(&td.server, sizeof(td.server));
    td.server.sin_family = AF_INET;
    td.server.sin_port = htons(serverport);
    td.server.sin_addr.s_addr = inet_addr(serverip.c_str());

    // 两个线程一个从td.sockfd里读，一个往td.sockfd里写，可以同时访问，是线程安全的
    pthread_t recvr, sender;
    pthread_create(&recvr, nullptr, recv_message, &td);
    pthread_create(&sender, nullptr, send_message, &td);

    pthread_join(recvr, nullptr);
    pthread_join(sender, nullptr);

    close(td.sockfd);
    return 0;
}
